<template>
  <div :class="classes || ''" class="column no-wrap bg-white-6 shadow-1 border-8 q-pa-md relative-position">
    <qx-form v-if="!nonSearch" v-model="searchForm" :option="searchOption" class="q-pb-md" isSearch @submit="initData">
      <template v-slot:menuRight="{ menuBind }">
        <q-btn icon="local_fire_department" outline text-color="primary" v-bind="menuBind" @click="handleHeatMap">
          {{ $t('MapCore.HeatMap') }}
        </q-btn>
      </template>
    </qx-form>
    <q-charts :loading="loading" :title="{ text: `设备运行统计${subheader}` }" classes="no-padding no-shadow col" format
              v-bind="chartBind"></q-charts>
    <q-btn v-if="nonSearch && false" class="absolute-top-right q-mr-md q-mt-md" icon="local_fire_department" outline
           text-color="indigo-14" @click="handleHeatMap">
      {{ $t('MapCore.HeatMap') }}
    </q-btn>
  </div>
  <TaskHeatMap v-model="heatMapVisible" v-model:heatMapSearch="searchForm"></TaskHeatMap>
</template>

<script setup>
import { i18n } from 'boot/i18n'
import TaskHeatMap from 'pages/Dashboard/Console/TaskHeatMap.vue'
import { date } from 'quasar'
import { postAPI } from 'src/api'
import { AGVTypes, taskStatus } from 'src/enum'
import { getRemoteData } from 'src/enum/ajaxRemoteData.js'
import { adaptFontSize } from 'src/utils/utils.js'
import { statisticalTypes } from 'src/views/TaskCore/enum.js'
import { computed, onMounted, ref, watch } from 'vue'

const props = defineProps({ nonSearch: Boolean, classes: String })

const AMRs = ref([])
const maps = ref([])
const rows = ref([])
const currentDate = new Date()
const xSiteName = ref('')
const searchForm = ref({})
const loading = ref(false)
const heatMapVisible = ref(false)

const subheader = computed(() => props.nonSearch ? ` (${searchForm.value.queryTime})` : '')
const queryType = computed(() => {
  if (searchForm.value.queryType === '1') return 'year'
  if (searchForm.value.queryType === '2') return 'month'
  return 'date'
})
const labelMap = computed(() => ({ agvCnt: '运行设备数' }))
const chartBind = computed(() => {
  const size = adaptFontSize(10), { nonSearch } = props
  return {
    charts: [{ type: 'bar' }], columns: ['timePeriod', 'agvCnt'], rows: rows.value, labelMap: labelMap.value,
    colors: ['#333FFF'], legend: { top: size * 0.5, right: nonSearch ? 'center' : 0, show: false },
    grid: { top: size * 4, bottom: size * 3.5, right: size * 4 },
    dataZoomNum: size * 5, xSite: {
      name: xSiteName.value, nameLocation: 'end',
      nameTextStyle: { align: 'center', verticalAlign: 'middle', padding: [size * 0.5, 0, 0, size * 0.5] }
    }
  }
})
const searchOption = computed(() => {
  const queryTime = date.formatDate(date.subtractFromDate(currentDate, { days: 1 }), 'YYYY-MM-DD')
  return {
    searchSpan: 6, searchLabelWidth: 70,
    column: [{
      label: `${i18n.t('Misc.StatisticsType')}`, field: 'queryType', type: 'select',
      options: statisticalTypes.value, clearable: false, searchValue: '3', change: queryTypeChange
    }, {
      label: `${i18n.t('Misc.StatisticsTime')}`, field: 'queryTime', type: queryType.value,
      searchValue: queryTime, clearable: false
    }, {
      label: `${i18n.t('MapCore.LocationMap')}`, field: 'mapCodeList', type: 'select', options: maps.value,
      props: { label: 'mapName', value: 'mapGroundCode' }, searchMultiple: true
    }, {
      label: `${i18n.t('AGVCore.AGVType')}`, field: 'taskCreateType', type: 'select',
      searchMultiple: true, options: AGVTypes.value, searchValue: '10'
    }, {
      label: `${i18n.t('AGVCore.AGVCode')}`, field: 'amrCode', type: 'select', options: AMRs.value,
      searchMultiple: true, props: { label: 'agvDeviceName', value: 'agvDeviceCode' }
    }, {
      label: `${i18n.t('TaskCore.TaskStatus')}`, field: 'taskStatus', type: 'select',
      options: taskStatus.value, searchMultiple: true
    }, {
      label: `${i18n.t('TaskCore.TaskTemplateCode')}`, field: 'taskTemplateCode'
    }]
  }
})
const handleHeatMap = () => heatMapVisible.value = true
const getAMRsAndMaps = () => {
  getRemoteData('agv_amr', '/yfagv/api/agvManage/list').then(data => AMRs.value = data)
  getRemoteData('agv_map', '/yfagv/api/agvMap/simpleList').then(data => (maps.value = data))
}
const queryTypeChange = val => {
  if (val === '1') searchForm.value.queryTime = date.formatDate(currentDate, 'YYYY')
  else if (val === '2') searchForm.value.queryTime = date.formatDate(currentDate, 'YYYY-MM')
  else if (val === '3') {
    searchForm.value.queryTime = date.formatDate(date.subtractFromDate(currentDate, { days: 1 }), 'YYYY-MM-DD')
  }
}
const formatSearchForm = () => {
  if (props.nonSearch) {
    searchForm.value.queryType = '3'
    searchForm.value.queryTime = date.formatDate(date.subtractFromDate(currentDate, { days: 1 }), 'YYYY-MM-DD')
    return { ...searchForm.value }
  }
  const params = { ...searchForm.value }
  if (params.amrCode) params.amrCode = params.amrCode.split(',')
  if (params.taskStatus) params.taskStatus = params.taskStatus.split(',')
  if (params.mapCodeList) params.mapCodeList = params.mapCodeList.split(',')
  if (params.taskCreateType) params.taskCreateType = params.taskCreateType.split(',')
  if (params.taskTemplateCode) params.taskTemplateCode = params.taskTemplateCode.split(',')
  return params
}
const getXName = queryType => {
  if (queryType === '2') return `${i18n.t('Day')}`
  if (queryType === '3') return `${i18n.t('Hour')}`
  return `${i18n.t('Month')}`
}
const initData = (_, done) => {
  loading.value = true
  postAPI('/yfagv/api/execL3TaskStat/queryAgvCntStat', formatSearchForm(), data => {
    if (searchForm.value.queryType === '3') {
      rows.value = (data || []).map(el => {
        el.timePeriod = `${el.timePeriod}`
        return el
      })
    } else rows.value = data || []
    done && done()
    loading.value = false
    xSiteName.value = getXName(searchForm.value.queryType)
  }, () => {
    done && done()
    rows.value = []
    xSiteName.value = ''
    loading.value = false
  })
}
watch(() => props.nonSearch, val => !val && getAMRsAndMaps(), { immediate: true })
onMounted(() => initData())
</script>